<script setup>
	import { ref, reactive } from 'vue'
	import datasetApi from '@/views/plugin/dashboard/api/datasetApi'
	import dataConnectorApi from '@/views/plugin/dashboard/api/dataConnectorApi'

	const emit = defineEmits(['loadData'])
	const visible = ref(false)
	const confirmLoading = ref(false)
	const formRef = ref()
	const dataConnectorList = ref([])

	const formState = reactive({
		id: '',
		name: '',
		description: '',
		dataConnectorId: undefined,
		config: { indicators: [] }
	})

	// 表单验证规则
	const rules = {
		name: [{ required: true, message: '请输入数据集名称', trigger: 'blur' }],
		dataConnectorId: [{ required: true, message: '请选择数据连接器', trigger: 'change' }]
	}

	// 打开弹窗
	const onOpen = (record) => {
		visible.value = true
		if (record) {
			Object.assign(formState, record)
		}
		// 获取数据连接器列表
		loadDataConnectors()
	}

	// 获取数据连接器列表
	const loadDataConnectors = async () => {
		try {
			const res = await dataConnectorApi.list()
			dataConnectorList.value = res
		} catch (error) {
			console.error('获取数据连接器列表失败:', error)
		}
	}

	// 关闭弹窗
	const onClose = () => {
		visible.value = false
		formRef.value?.resetFields()
		Object.assign(formState, {
			id: '',
			name: '',
			description: '',
			dataConnectorId: undefined,
			config: { indicators: [] }
		})
	}

	// 提交表单
	const onSubmit = () => {
		formRef.value.validate().then(() => {
			confirmLoading.value = true
			datasetApi
				.save(formState)
				.then(() => {
					onClose()
					emit('loadData')
				})
				.finally(() => {
					confirmLoading.value = false
				})
		})
	}

	// 暴露方法给父组件
	defineExpose({
		onOpen
	})
</script>

<template>
	<a-drawer :open="visible" :title="formState.id ? '编辑数据集' : '新增数据集'" @close="onClose" :width="500">
		<a-form ref="formRef" :model="formState" :rules="rules" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
			<a-form-item label="数据集名称" name="name">
				<a-input v-model:value="formState.name" placeholder="请输入数据集名称" />
			</a-form-item>
			<a-form-item label="数据连接器" name="dataConnectorId">
				<a-select
					:disabled="!!formState.id"
					v-model:value="formState.dataConnectorId"
					placeholder="请选择数据连接器"
					:options="
						dataConnectorList.map((item) => ({
							value: item.id,
							label: item.name
						}))
					"
				/>
			</a-form-item>
			<a-form-item label="描述" name="description">
				<a-textarea v-model:value="formState.description" placeholder="请输入描述信息" :rows="4" />
			</a-form-item>
		</a-form>
		<template #footer>
			<div class="flex justify-end">
				<a-button style="margin-right: 8px" @click="onClose">取消</a-button>
				<a-button type="primary" :loading="confirmLoading" @click="onSubmit">确定</a-button>
			</div>
		</template>
	</a-drawer>
</template>
